package com.ksyun.ks3.services.request;

import com.ksyun.ks3.exception.Ks3ClientException;
import com.ksyun.ks3.model.HttpHeaders;
import com.ksyun.ks3.model.HttpMethod;
import com.ksyun.ks3.util.Md5Utils;
import com.ksyun.ks3.util.StringUtils;

import java.io.ByteArrayInputStream;

public class PutBucketPolicyRequest extends Ks3HttpRequest {

    private static final long serialVersionUID = 28505422321283770L;

    private String policy;

    public PutBucketPolicyRequest(String bucketName) {
        super.setBucketname(bucketName);
    }

    public PutBucketPolicyRequest(String bucketName, String policy) {
        this(bucketName);
        this.policy = policy;
    }

    @Override
    protected void setupRequest() throws Ks3ClientException {

        this.setHttpMethod(HttpMethod.PUT);
        this.addParams("policy", "");

        this.addHeader(HttpHeaders.ContentType, "application/json");
        this.addHeader(HttpHeaders.ContentMD5, Md5Utils.md5AsBase64(policy.getBytes()));
        this.addHeader(HttpHeaders.ContentLength, String.valueOf(policy.getBytes().length));
        this.setContentLength(policy.getBytes().length);
        this.setInputStreamBody(new ByteArrayInputStream(policy.getBytes()));
    }

    public void validateParams() throws Ks3ClientException {

        if (StringUtils.isBlank(this.getBucketname())) {
            throw new Ks3ClientException("bucket name is not correct");
        }
        if (this.policy == null) {
            throw new Ks3ClientException("policy is not correct");
        }

    }

}
